#include <stdio.h>
#include <stdlib.h>
#include "../heads/ArrayList.h"

// 初始化顺序表
ArrayList createArrayList(int initialCapacity) {
    ArrayList list;
    list.array = (int *)malloc(initialCapacity * sizeof(int));
    if (list.array == NULL) {
        // 处理内存分配失败的情况
        fprintf(stderr, "顺序表初始化失败：无法为顺序表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    list.size = 0;
    list.capacity = initialCapacity;
    return list; // 返回新创建的顺序表
}

// 自动扩容函数（static意味着函数只能在定义它的源文件中被调用）
static void resizeArrayList(ArrayList *list) {
    int newCapacity = list->capacity * 2;  // 扩容到当前容量的两倍
    int *newArray = (int *)realloc(list->array, newCapacity * sizeof(int));
    if (newArray) {
        list->array = newArray;
        list->capacity = newCapacity;
    } else {
        // 如果内存分配失败，可以根据需要处理错误
        fprintf(stderr, "顺序表扩容失败：无法为顺序表分配内存！\n");
        exit(EXIT_FAILURE);
    }
}

void addElement(ArrayList *list, int element) {
    if (list->size == list->capacity) {
        resizeArrayList(list);
    }
    list->array[list->size++] = element;
}

void removeElement(ArrayList *list, int index) {
    if (index < 0 || index >= list->size) {
        fprintf(stderr, "数组索引越界！\n");
        return;
    }
    for (int i = index; i < list->size - 1; i++) {
        list->array[i] = list->array[i + 1];
    }
    list->size--;
}

void setElement(ArrayList *list, int index, int newValue) {
    if (index < 0 || index >= list->size) {
        fprintf(stderr, "数组索引越界！\n");
        return;
    }
    list->array[index] = newValue;
}

int getElement(ArrayList *list, int index) {
    if (index < 0 || index >= list->size) {
        fprintf(stderr, "数组索引越界！\n");
        return -1; // or some other invalid value indicating error
    }
    return list->array[index];
}

void destroyArrayList(ArrayList *list) {
    free(list->array);
    list->array = NULL;
    list->size = 0;
    list->capacity = 0;
}
